package com.mohan.system.auth.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.fastjson.TypeReference;
import com.mohan.calligraphy.constant.CalligraphyHttpStatus;
import com.mohan.calligraphy.constant.RedisConstant;
import com.mohan.calligraphy.dto.SystemUserRegistry;
import com.mohan.calligraphy.exception.BusinessException;
import com.mohan.calligraphy.result.R;
import com.mohan.system.auth.feign.SystemManageFeign;
import com.mohan.system.auth.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private SystemManageFeign systemManageFeign;

    @Override
    public void getLoginImageCode(String uuid, ServletResponse response) throws IOException {
        LineCaptcha loginCaptcha = CaptchaUtil.createLineCaptcha(120, 50, 4, 48);
        String code = loginCaptcha.getCode();
        code = code.toLowerCase();
        redisTemplate
                .opsForValue()
                .set(RedisConstant.REDIS_PREFIX_LOGIN_CODE + uuid,
                        code,
                        RedisConstant.REDIS_EXPIRE_Captcha,
                        TimeUnit.SECONDS);
        loginCaptcha.write(response.getOutputStream());
    }

    @Override
    public String login(SystemUserRegistry userRegistry) {
        // 如果验证码不存在
        if (StringUtils.isBlank(userRegistry.getCode())) {
            throw new BusinessException(CalligraphyHttpStatus.CalligraphyErrorMessage.CAPTCHA_INPUT);
        }
        String key = RedisConstant.REDIS_PREFIX_LOGIN_CODE + userRegistry.getUuid().toLowerCase();
        String code = userRegistry.getCode();
        String redisCode = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(redisCode)) {
            throw new BusinessException(CalligraphyHttpStatus.CalligraphyErrorMessage.CAPTCHA_NOT_FOUND);
        }
        // 如果验证码正确就远程调用
        if (redisCode.equals(code)) {
            redisTemplate.delete(key);
            try {
                R r = systemManageFeign.login(userRegistry);
                String token = r.getData(new TypeReference<String>() {});
                return token;
            } catch (BusinessException e) {
                throw new BusinessException(e);
            }
        }else {
            throw new BusinessException(CalligraphyHttpStatus.CalligraphyErrorMessage.CAPTCHA_ERROR);
        }
    }

}
